<!-- 首页 -->
<template>
	<view class="home_wrap">
		<!-- 空白页 -->
		<t-empty v-if="!hasTemplate" :emptyData="emptyData"></t-empty>
		<view v-else class="home_content" :style="pageBgColor">
			<!-- 自定义数据 -->
			<block v-if="template" v-for="(item, index) in template" :key="index">
				<!-- 导航栏 -->
				<view class="head-nav" v-if="item.type === 'header' && item.content">
					<u-navbar
						backIconName
						:borderBottom="false"
						:background="item.content.bgcolor ? { background: item.content.bgcolor } : navbar.background"
						:backTextStyle="navbar.backTextStyle"
						:backText="initData.info.name"
					>
						<view class="ma20 mr50 u-flex u-row-center u-col-center" @tap="$Router.push({ path: '/pages/goods/list' })">
							<u-search placeholder="搜索" disabled v-model="keyword" :showAction="false" height="54"></u-search>
						</view>
					</u-navbar>
				</view>
				<!-- 门店 -->
				<view class="location-share-wrap x-bc ma20" v-if="item.type === 'store' && item.content" :style="'background:' + item.content.bgcolor">
					<view class="location-box ml20  x-f" @tap="$Router.push({ path: '/pages/app/store/location' })">
						<view class="store-img-wrap x-c mr20" v-if="storeInfo.id"><image class="store-img" :src="storeInfo.image_first" mode=""></image></view>
						<view class="">
							<view class="location-address" :style="'color:' + item.content.color">
								{{ storeInfo.id ? storeInfo.name : '请选择附近门店' }}
								<text class="cuIcon-unfold ml10"></text>
							</view>
						</view>
					</view>
					<view class="share-box x-f" @tap="onShare" :style="'color:' + item.content.color">
						<text class="share-icon iconfont icon-fenxiang"></text>
						<text class="share-text ml10">分享</text>
					</view>
				</view>
				<!-- 轮播 -->
				<sh-banner v-if="item.type === 'banner' && item.content" :detail="item.content"></sh-banner>
				<!-- 菜单 -->
				<sh-menu v-if="item.type === 'menu' && item.content" :detail="item.content" :menu="item.content.style" :imgW="94"></sh-menu>
				<!-- 推荐商品 -->
				<sh-hot-goods
					v-if="(item.type === 'goods-list' && item.content.type === 2) || (item.type === 'goods-group' && item.content.type === 2)"
					:detail="item.content"
				></sh-hot-goods>
				<!-- 大图商品 -->
				<block v-if="(item.type === 'goods-list' && item.content.type === 1) || (item.type === 'goods-group' && item.content.type === 1)">
					<sh-big-card :detail="item.content"></sh-big-card>
				</block>
				<!-- 广告魔方 -->
				<sh-adv v-if="item.type === 'adv'" :detail="item.content"></sh-adv>
				<!-- 优惠券 -->
				<sh-coupon v-if="item.type === 'coupons'" :detail="item.content"></sh-coupon>
				<!-- 功能列表 -->
				<sh-nav v-if="item.type === 'nav-list'" :detail="item.content"></sh-nav>
				<!-- 九宫格列表 -->
				<sh-grid v-if="item.type === 'grid-list'" :detail="item.content"></sh-grid>
				<!-- 功能标题 -->
				<sh-title-card v-if="item.type === 'title-block'" :detail="item.content"></sh-title-card>
			</block>

			<!-- tabs分类 -->
			<view v-if="categoryTabsTemplate">
				<u-sticky ref="uSticky" :h5NavHeight="0" @fixed="stickyTabs" @unfixed="unStickyTabs" :bgColor="isSticky ? '#fff' : '#f6f6f6'" :offsetTop="stickyTop" enable>
					<view class="tabs-wrap" :style="isSticky ? 'border-bottom:1px solid #eee' : ''">
						<u-tabs
							bold="bold"
							height="120"
							custom
							:bgColor="isSticky ? '#fff' : '#f6f6f6'"
							barWidth="166"
							:barStyle="tab.barStyle"
							active-color="#d90000"
							:list="tabsList"
							@change="tabChange"
							:current="tabCurrent"
						></u-tabs>
					</view>
				</u-sticky>
				<view class="goods-wrap x-f">
					<u-waterfall v-model="goodsList" ref="uWaterfall" v-if="goodsList.length">
						<template v-slot:left="{ leftList }">
							<view class="goods-item mb20" v-for="leftGoods in leftList" :key="leftGoods.id">
								<t-goods-card
									:image="leftGoods.image"
									:title="leftGoods.title"
									:subtitle="leftGoods.subtitle"
									:price="leftGoods.price"
									:originPrice="leftGoods.original_price"
									:detail="leftGoods"
									@click="$Router.push({ path: '/pages/goods/detail/index', query: { id: leftGoods.id } })"
								></t-goods-card>
							</view>
						</template>
						<template v-slot:right="{ rightList }">
							<view class="goods-item mb20" v-for="rightGoods in rightList" :key="rightGoods.id">
								<t-goods-card
									:image="rightGoods.image"
									:title="rightGoods.title"
									:subtitle="rightGoods.subtitle"
									:price="rightGoods.price"
									:originPrice="rightGoods.original_price"
									:detail="rightGoods"
									@click="$Router.push({ path: '/pages/goods/detail/index', query: { id: rightGoods.id } })"
								></t-goods-card>
							</view>
						</template>
					</u-waterfall>
					<view class="x-c" style="width: 100%;">
						<!-- 空数据 -->
						<u-empty :style="{ 'margin-bottom': isEmpty ? '300rpx' : '0' }" :show="isEmpty" marginTop="300" mode="list"></u-empty>
						<!-- 更多 -->
						<u-loadmore v-show="!isEmpty" height="80rpx" :status="loadStatus" icon-type="flower" color="#ccc" />
					</view>
				</view>
			</view>

			<!-- 分享组件 -->
			<t-share v-if="showShare" v-model="showShare" @setShareInfo="setShareInfo" :shareData="storeInfo" :posterType="'store'"></t-share>
			<!-- 登录提示 -->
			<t-login-modal></t-login-modal>
			<!-- 连续弹窗提醒 -->
			<t-notice-modal v-if="showNoticeModal"></t-notice-modal>
			<!-- 悬浮按钮 -->
			<t-float-btn></t-float-btn>
			<!-- 购买提示 -->
			<swiper class="silde-tip-wrap" @change="changeBuySwiper" circular skip-hidden-item-layout vertical :autoplay="autoplay" :interval="3000" :duration="3000">
				<swiper-item class="silde-box" v-for="(item, index) in orderRemindLog" :key="index">
					<view class="x-f silde-item" :class="{ 'move-in': buyCurrent == index, 'move-out': buyCurrent == index - 1 }">
						<image class="item-img" :src="item.avatar" mode="aspectFill"></image>
						<text class="item-text">{{ item.remind }}</text>
					</view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>

<script>
import shBanner from './components/sh-banner.vue';
import shHotGoods from './components/sh-hot-goods.vue';
import shMenu from './components/sh-menu.vue';
import shAdv from './components/sh-adv.vue';
import shCoupon from './components/sh-coupon.vue';
import shNav from './components/sh-nav.vue';
import shGrid from './components/sh-grid.vue';
import shTitleCard from './components/sh-title-card.vue';
import shBigCard from './components/sh-big-card.vue';

import { mapMutations, mapActions, mapState } from 'vuex';
let systemInfo = uni.getSystemInfoSync();
export default {
	components: {
		shBanner,
		shHotGoods,
		shTitleCard,
		shMenu,
		shAdv,
		shGrid,
		shCoupon,
		shNav,
		shBigCard
	},
	data() {
		return {
			navbar: {
				//navbar配置
				backTextStyle: {
					color: '#fff',
					'font-size': '35rpx',
					'font-weight': '800'
				},
				background: {
					background: '#d90000'
				}
			},
			autoplay: true,
			isSticky: false,
			isEmpty: true,
			tab: {
				barStyle: {
					background: 'none',
					height: '44rpx'
				}
			},
			tabCurrent: 0, //tabs初始下标
			tabsList: [], //tabs列表
			buyCurrent: 0, //购买提示
			orderRemindLog: [], //提示列表
			showShare: false, //分享
			showNoticeModal: true, //弹窗提醒
			triggered: false, //下拉刷新
			_freshing: false, //下拉刷新状态
			emptyData: {
				//置空页
				img: this.$IMG_URL + '/empty/template_empty.png',
				tip: '暂未找到模板，赶快去装修吧~'
			},
			categoryId: 0,
			ids: '',
			categoryTabsTemplate: null,
			goodsList: [],
			loadStatus: 'loadmore', //loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
			currentPage: 1,
			lastPage: 1
		};
	},
	computed: {
		...mapState({
			template: state => state.init.templateData?.home,
			hasTemplate: state => state.init.hasTemplate,
			cartNum: state => state.cart.cartNum,
			storeInfo: ({ user }) => user.storeInfo,
			initData: ({ init }) => init.initData,
			pageBgColor() {
				if (this.template?.[0]) {
					let color = this.template?.[0]?.content?.bgcolor;
					return `background: linear-gradient(${color} 500rpx, #f6f6f6 700rpx);`;
				}
			},
			stickyTop() {
				let height = systemInfo.platform == 'ios' ? 38 : 44;
				let top = (height + systemInfo.statusBarHeight) * 2;
				return top;
			}
		})
	},
	onPullDownRefresh() {
		this.init();
	},
	async onLoad(options) {
		let storeID = uni.getStorageSync('storeID');
		if (storeID) {
			this.getStoreInfo(storeID);
		} else if (!uni.getStorageSync('storeInfo')) {
			this.$Router.push({
				path: '/pages/app/store/location'
			});
		}

		if (this.template && this.template.length) {
			let lastTemplate = this.template[this.template.length - 1];
			if (lastTemplate && lastTemplate.type == 'category-tabs') {
				this.categoryTabsTemplate = lastTemplate
				this.ids = this.template[this.template.length - 1]?.content?.ids;
				this.ids && this.getGoodsTabs(this.ids);
				
				// 触底监听
				uni.$on('uOnReachBottom', data => {
					if (this.currentPage < this.lastPage) {
						this.currentPage += 1;
						this.getGoodsList();
					}
				});
			}
		}
	},
	onShow() {
		this.autoplay = true;
		if (uni.getStorageSync('userInfo')) {
			this.$store.commit('CART_NUM', this.cartNum);
			this.getOrderRemind();
		}
	},
	onHide() {
		this.autoplay = false;
	},
	methods: {
		...mapMutations(['CART_NUM']),
		...mapActions(['getAppInit', 'getTemplate', 'getStoreInfo']),
		// 初始化
		init() {
			return Promise.all([this.getAppInit(), this.getTemplate(), this.getOrderRemind()]).then(() => {
				uni.stopPullDownRefresh();
			});
		},

		// 获取分类商品tabs
		getGoodsTabs(ids) {
			let that = this;
			that.$api('category.list', {
				ids: ids
			}).then(res => {
				if (res.code === 1) {
					that.tabsList = res.data;
					that.categoryId = that.tabsList[0]?.id;
					that.getGoodsList();
					that.$refs.uSticky.initObserver();
				}
			});
		},

		// 商品列表
		getGoodsList() {
			let that = this;
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			that.loadStatus = 'loading';
			that.$api('goods.lists', {
				category_id: that.categoryId,
				page: that.currentPage
			}).then(res => {
				uni.hideLoading();
				if (res.code === 1) {
					that.goodsList = [...that.goodsList, ...res.data.data];
					that.isEmpty = !that.goodsList.length;
					that.lastPage = res.data.last_page;
					if (that.currentPage < res.data.last_page) {
						that.loadStatus = 'loadmore';
					} else {
						that.loadStatus = 'nomore';
					}
				}
			});
		},

		// tabs
		tabChange(index) {
			if (this.tabCurrent !== index) {
				this.tabCurrent = index;
				this.categoryId = this.tabsList[index].id;
				this.goodsList = [];
				this.currentPage = 1;
				this.lastPage = 1;
				this.getGoodsList();
				this.$refs.uSticky.initObserver();
			}
		},
		stickyTabs() {
			this.isSticky = true;
			this.$refs.uSticky.initObserver();
		},
		unStickyTabs() {
			this.isSticky = false;
			this.$refs.uSticky.initObserver();
		},

		// 购买提示
		changeBuySwiper(e) {
			this.buyCurrent = e.detail.current;
		},

		// 购物数据
		getOrderRemind() {
			let that = this;
			that.$api('order.orderRemind').then(res => {
				if (res.code === 1) {
					that.orderRemindLog = res.data;
				}
			});
		},
		// 路由跳转
		jump(path, parmas) {
			this.$Router.push({
				path: path,
				query: parmas
			});
		},
		// 分享门店
		onShare() {
			if (!uni.getStorageSync('storeInfo') || !uni.getStorageSync('userInfo')) {
				this.$Router.push({
					path: '/pages/app/store/location'
				});
			} else {
				this.showShare = true;
			}
		},
		// 组件里面无法更改mixin。
		setShareInfo(e) {
			this.shareInfo = e;
		}
	}
};
</script>

<style lang="scss" scoped>
.home_wrap {
	&:-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
		display: none;
	}
}
.home_content {
	background: linear-gradient($t-mainColor 500rpx, #f6f6f6 700rpx);
}
// tabs分类
.tabs-wrap {
	.tab-active {
		background: url($IMG_URL+'/gr_index_tab_active.png') no-repeat;
		background-size: 100%;
		color: #fff;
		width: 166rpx;
		height: 44rpx;
		font-size: 22rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		bottom: -44rpx;
	}
}
.goods-wrap {
	flex-wrap: wrap;
	min-height: 1000rpx;
	padding: 20rpx;
	width: 750rpx;
	align-items: flex-start;
	align-content: flex-start;
	.goods-item {
		margin-right: 20rpx;
		margin-bottom: 20rpx;

		&:nth-child(2n) {
			margin-right: 0;
		}
	}
}
// 定位门店
.location-share-wrap {
	width: 700rpx;
	height: 60rpx;
	background: rgba(#fff, 0.2);
	border-radius: 10rpx;
	.location-box {
		.store-img-wrap .store-img {
			width: 40rpx;
			height: 40rpx;
			border-radius: 50%;
		}
		.location-address {
			font-size: 26rpx;
			font-weight: 500;
			color: #ffffff;
		}
		.cuIcon-unfold {
			color: #ffffff;
			font-size: 26rpx;
			line-height: 30rpx;
		}
	}
	.share-box {
		color: #fff;
		font-size: 26rpx;
		margin-right: 20rpx;
	}
}
// 购买提示
@keyframes movein {
	0% {
		opacity: 0;
	}
	100% {
		opacity: 1;
	}
}
@keyframes moveout {
	0% {
		opacity: 1;
	}
	100% {
		opacity: 0;
	}
}

.silde-tip-wrap {
	position: fixed;
	left: 30rpx;
	top: 300rpx;
	height: 120rpx;
	width: 750rpx;
	z-index: 99;
	pointer-events: none;
	.move-in {
		animation: movein 2s;
	}
	.move-out {
		animation: moveout 2s;
	}
	.silde-box {
		.silde-item {
			height: 64rpx;
			background-color: rgba(#000, 0.4);
			border-radius: 32rpx;
			padding: 0 10rpx;
			position: absolute;
			margin: 20rpx 0;
			.item-img {
				width: 50rpx;
				height: 50rpx;
				border-radius: 50%;
				margin-right: 10rpx;
			}
			.item-text {
				font-size: 24rpx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #fff;
			}
		}
	}
}
</style>
